package top.yoahh.security.config;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义登录失败的相应回调函数
 */
@Slf4j
@Component
public class AuthenticationFailureHandlerConfig implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        log.info("==========>登录失败，失败原因",e.getMessage());
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        PrintWriter out = httpServletResponse.getWriter();
        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        Map<String, Object> map = new HashMap<>();
        map.put("status", HttpServletResponse.SC_UNAUTHORIZED);
        if (e instanceof LockedException) {
            map.put("msg", "账户被锁定，登陆失败！");
        } else if (e instanceof BadCredentialsException) {
            map.put("msg", "账户名或密码输入错误，登陆失败！");
        } else if (e instanceof DisabledException) {
            map.put("msg", "账户被禁用，登陆失败！");
        } else if (e instanceof AccountExpiredException) {
            map.put("msg", "账户已过期，登陆失败！");
        } else if (e instanceof CredentialsExpiredException) {
            map.put("msg", "密码已过期，登陆失败！");
        } else {
            map.put("msg", "登陆失败！");
        }
        ObjectMapper om = new ObjectMapper();
        out.write(om.writeValueAsString(map));
        out.flush();
        out.close();

    }
}
